package com.bifrost.task;

import com.bifrost.service.TransactionService;
import com.bifrost.task.support.FTPClientPool;
import com.bifrost.task.support.FtpConnectWrapper;
import com.bifrost.util.DateTimeUtil;
import com.bifrost.util.FTPUtil;
import com.xxl.job.core.handler.IJobHandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * Author by yanxiaobo
 * Date on 2018/6/12$.
 */
public abstract class BaseSendTask extends IJobHandler{
    Logger logger = LoggerFactory.getLogger(TransactionService.class);

    public static final String FILE_EXTENSION = ".xml";
    public static final String REPORT_FILE_NAME_PREFIX = "MT_SEND_POSSYPAY";
    public static final String RECEIPT_FILE_NAME_PREFIX = "MT_POS_SALES_DATA";
    private static final String TEMP_PATH="temp";

    @Autowired
    FTPClientPool ftpClientPool;
    @Autowired
    @Qualifier("RichBaseFTPClientPool")
    FTPClientPool richBaseFTPClientPool;
    @Autowired
    TransactionService transactionService;
    //static String localTempPath;
    @Value("${sap.report.path}")
    String sapReportPath;
    @Value("${sap.receipt.path}")
    String sapReceiptPath;
    @Value("${richBase.receipt.path}")
    String richBaseReceiptPath;

   /* static {
        String path = Class.class.getClass().getResource("/").getPath();
        int index = path.indexOf("target");
        localTempPath = path.substring(0, index) + "temp";
    }*/

    protected File getUploadFile(String xml, String fileName) {
        fileName = fileName + "-" +
                DateTimeUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + "-" + System.nanoTime();
        File file = new File(TEMP_PATH + File.separator+ fileName + FILE_EXTENSION);
        //FileOutputStream stream = null;
        try {
            FileUtils.writeByteArrayToFile(file, xml.getBytes());

            /*if (!file.exists()) {
                file.setWritable(true);
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            stream = new FileOutputStream(file);
            stream.write(xml.getBytes("UTF-8"));
            stream.flush();*/
        } catch (IOException e) {
            logger.error("将资源写入本地文件过程出错:{}", e);
            throw new RuntimeException("将资源写入本地文件过程出错");
        } finally {
            /*if (null != stream) {
                try {
                    stream.close();
                    stream = null;
                } catch (IOException e) {
                    logger.error("关闭资源失败:{}", e);
                    throw new RuntimeException("关闭资源失败");
                }
            }*/
        }
        return file;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Uploader {

        private String param;

        /**
         * 上传文件
         *
         * @param xml 要上传的资源
         * @return true上传成功 false相反
         */
        public boolean upload(String xml){

            //获取要上传的文件
            File file = getUploadFile(xml,RECEIPT_FILE_NAME_PREFIX);
            boolean result = false;

            FTPClientPool clientPool = null;
            //选择上传地址
            String connectionPath = null;
            switch (param){
                case "richBaseReceipt":
                    connectionPath = richBaseReceiptPath;
                    clientPool = richBaseFTPClientPool;
                    break;
                case "sapReceipt":
                    connectionPath = sapReceiptPath;
                    clientPool = ftpClientPool;
                    break;
                case "sapReport":
                    connectionPath = sapReportPath;
                    clientPool = ftpClientPool;
                    break;
                    default:break;
            }
            Assert.notNull(connectionPath,"上传小票地址不能为空");

            //没有正确获取file文件依然返回false
            return sendToFtp(clientPool,connectionPath,file, result);


        }
    }

    private boolean sendToFtp(FTPClientPool clientPool ,String connectionPath , File file,  boolean result) {
        FtpConnectWrapper ftpConnectWrapper = null ;
        // //开始上传文件
        if (null != file) {
            try {
                ftpConnectWrapper = clientPool.borrowObject();
                result = FTPUtil.upload(file, connectionPath,ftpConnectWrapper);
            } catch (Exception e) {
                logger.error("上传文件错误:{}", e);
                throw new RuntimeException(e.getMessage());
            } finally {
                if (null != file)
                    file.delete();
                try {
                    if (null != ftpConnectWrapper)
                        clientPool.returnObject(ftpConnectWrapper);
                } catch (Exception e) {
                    logger.error("归还ftp连接出错：{}",e);
                    throw new RuntimeException("归还ftp连接出错");
                }
            }
        }
        return result;
    }

}
